<?php

class RSSReader implements Iterator
{
    private $xmlObject; //simpleXML objekti
    private $resultSet; //tulostaulukko
    private $limit;     //määrä
    private $iterator = 0;
    private $timestamps;
    private $meta;      //tietoja uutisvirrasta

    const sortASC = SORT_ASC;
    const sortDESC = SORT_DESC;

    /* ottaa argumentikseen RSS virran osoitteen ja tarvittaessa halutun elementtien määrän */
    public function __construct($url, $limit = 99999)
    {
        $this->limit = $limit;
        $this->timestamps = array();
        $this->resultSet = array();
        $this->meta = array();
		
		// proxyt respectively
		
		$proxylist = array("akamai01.rev.net", 'akamai02.rev.net', "akamai03.rev.net", 'akamai04.rev.net', "akamai05.rev.net", 'akamai06.rev.net', "akamai07.rev.net", 'vds.itank.ru', "technischer-support.com", 'sd-203.dedibox.fr');
		$proxyport = array("80", '80', "80", '80', "80", '80', "80", '3128', "3128", '3128');
		$lastproxy = "";
		$rand = 0;
		
		$i = 0; # loopataan muilla proxyilla jos yks on down
		while (($this->xmlObject == false) and ($i <= count($proxylist)))
		{	
			if ($i > 0) print "$lastproxy not working!\n";
			$i++;
			//arvotaan proxy (ei oteta sitä joka oli viimeks ja ei toiminu)
			while ($proxylist[$rand] == $lastproxy) $rand = mt_rand(0,(count($proxylist)));
			
			// ladataan ilman proxya
			if ($rand == count($proxylist)) $this->xmlObject = @simplexml_load_file($url);
			// ladataan proxyn kanssa
			else
			{
				$curl = curl_init();
				$lastproxy = $proxylist[$rand]; # otetaan nimi ylös sitä varten jos ei toimi
				//proxy
				curl_setopt($curl, CURLOPT_PROXY, $proxylist[$rand]);
				curl_setopt($curl, CURLOPT_PROXYPORT, $proxyport[$rand]);
				
				//lataus
				curl_setopt($curl, CURLOPT_URL, $url);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

				file_put_contents("temp", curl_exec($curl));
				curl_close($curl);

				$this->xmlObject = @simplexml_load_file("temp");
				unlink("temp");
			}
		}
		
        if($this->xmlObject == false) {
            throw new Exception("Unable to get/parse data from $url"); //XML dataa ei kyetty jäsentämään
        }
        $this->parseData();
    }
   
    private static function parseTime($timeStr)
    {
        $month = array('Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6,'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12);   
        $temp = sscanf($timeStr,"%s %d %s %d %d:%d:%d");
        $temp[2] = $month[$temp[2]];
        return mktime($temp[4],$temp[5],$temp[6],$temp[2],$temp[1],$temp[3]);
    }
    private function parseData()
    {
        $current = 0;
        /* haetaan virran otsikko, kuvaus ja URL */
        $this->meta[0] = (string)$this->xmlObject->channel->title;
        $this->meta[1] = (string)$this->xmlObject->channel->link;
        $this->meta[2] = (string)$this->xmlObject->channel->description;

        /* käydään virtaa läpi kunnes raja tulee vastaa tai kaikki elementit on käyty läpi */
        foreach($this->xmlObject->channel->item as $feedItem) {
            $this->timestamps[] = $timestamp = self::parseTime($feedItem->pubDate);
            $url = (string)$feedItem->link;
            $title = (string)$feedItem->title;
            $this->resultSet[] = array($timestamp,$url,$title);
            if(++$current > $this->limit)
                break;
        }
        /* vapautetaan resursseja */
        unset($this->xmlObject);
    }
    /* järjestää elementit kellonajan ja päivämäärän mukaan, joko nousevasti
    * (RSSReader::sortASC) tai laskevasti (RSSReader::sortDESC)
    */
    public function sort($order = self::sortDESC)
    {
        array_multisort($this->timestamps,$order,$this->resultSet);
    }
    public function getLink()
    {
        return $this->meta[1];
    }
    /* palauttaa RSS virran otsikon */
    public function getTitle()
    {
        return $this->meta[0];
    }
    /* palauttaa RSS virran kuvauksen */
    public function getDescription()
    {
        return $this->meta[2];   
    }
    /* implementoidaan Iterator iteraattorissa määritelty metodin current() */
    /* Palauttaa taulukon, joka sisältää data, johon iteraattori tällä hetkellä osoittaa */
    public function current()
    {
        $res = array('timestamp' => $this->resultSet[$this->iterator][0],
            'url' => $this->resultSet[$this->iterator][1],
            'title' => $this->resultSet[$this->iterator][2]);
        return array_merge($res,$this->resultSet[$this->iterator]);
    }
    /* implementoidaan Iterator iteraattorissa määritelty metodin next() */
    /* siirrytään seuraavaan elementtiin */
    public function next()
    {
        $this->iterator++;
    }
    /* implementoidaan Iterator iteraattorissa määritelty metodin key() */
    public function key()
    {
        return $this->iterator;
    }
    /* implementoidaan Iterator iteraattorissa määritelty metodin rewind() */
    /* siirrytään ensimmäiseen elementtiin */
    public function rewind()
    {
        $this->iterator = 0;
    }
    /* implementoidaan Iterator iteraattorissa määritelty metodin valid() */
    /* tutkitaan onko uusia elementtejä vielä jäljellä */
    public function valid()
    {
        return ((count($this->resultSet) > $this->iterator) ? true : false);
    }

}

function pipes($nimi, $divclass, $osoite)
{
    $rss = new RSSReader($osoite);
	$rss->sort(RSSReader::sortDESC);

	$output = "";
	$i = 0;
	foreach($rss as $item) $i++;
	if ($i > 0) {
		
		$output .= '<div class="age_'.$divclass.'">'.$nimi.'</div>';
		
		$output .= '<p>';
		foreach($rss as $item) {
			
			if (stristr($item['url'], "msnbc.msn.com")) $output .= '<img src="/images/msnbc.ico">'; #tänne vaan kuvia vastaamaan noita feedien urleja
			else if (stristr($item['url'], "bbc.co.uk")) $output .= '<img src="/images/bbc.ico">';
			else if (stristr($item['url'], "businessweek.com")) $output .= '<img src="/images/businessweek.ico">';
			else if (stristr($item['url'], "cnn.com")) $output .= '<img src="/images/cnn.ico">';
			else if (stristr($item['url'], "copyblogger.com")) $output .= '<img src="/images/copyblogger.ico">';
			else if (stristr($item['url'], "foxbusiness.com")) $output .= '<img src="/images/fox_business.ico">';
			
			else if (stristr($item['url'], "ft.com")) $output .= '<img src="/images/ft.ico">';
			else if (stristr($item['url'], "guardian.co.uk")) $output .= '<img src="/images/guardian.ico">';
			else if (stristr($item['url'], "marketwatch.com")) $output .= '<img src="/images/marketwatch.ico">';
			else if (stristr($item['url'], "newsweek.com")) $output .= '<img src="/images/newsweek.ico">';
			else if (stristr($item['url'], "businessweek.com")) $output .= '<img src="/images/businessweek.ico">';
			
			else if (stristr($item['url'], "reuters.com")) $output .= '<img src="/images/reuters.ico">';
			else if (stristr($item['url'], "telegraph.co.uk")) $output .= '<img src="/images/telegraph.ico">';
			else if (stristr($item['url'], "timesonline.co.uk")) $output .= '<img src="/images/timesonline.ico">';
			else if (stristr($item['url'], "yahoo.com")) $output .= '<img src="/images/yahoo.ico">';
			else if (stristr($item['url'], "mymoneyblog")) $output .= '<img src="/images/mymoneyblog.ico">';
			
			else if (stristr($item['url'], "forbes.com")) $output .= '<img src="/images/forbes.ico">';
			else if (stristr($item['url'], "MyMint")) $output .= '<img src="/images/mint.ico">';
			else if (stristr($item['url'], "YourMoneyMoneyMusings")) $output .= '<img src="/images/mdmproofing.ico">';
			else if (stristr($item['url'], "ncnblog")) $output .= '<img src="/images/ncnblog.ico">';
			else if (stristr($item['url'], "freemoneyfinance")) $output .= '<img src="/images/free_money_finance.ico">';
			
			
			else $output .= '<img src="/images/bullet.ico">'; #ja tohon joku lehmän kuva kun on tuntematon feedi kyseessä :p*/
			
			if (strlen($item['title']) > 80) $item['title'] = substr($item['title'], 0, 77)."...";
			
		    // säädetään encodingin kanssa
		    $title = $item['title'];
		    $title = str_replace('â', '´',  $title);
		    $title = str_replace('’', '´', $title);
		    $title = str_replace('‘', '`', $title);
		    $title = str_replace('Â', '', $title);
		    $title = str_replace('€', '&euro;', $title);
		    $title = str_replace('–', '&ndash;', $title); 
		    $title = str_replace('—', '&mdash;', $title);
		    $title = str_replace('Ã©', '&eacute;', $title); 
		    
		    $title = htmlentities($title);
		    $title = str_replace('&Acirc;', '', $title);
		    $title = str_replace('&amp;', '&', $title);
		    
		    /*$title = ereg_replace("[^A-Za-z0-9!\"'£$%#‚&?@/\\_;< >=.-]","",$item['title']);
			$title = htmlspecialchars_decode(htmlentities($title));
			if (preg_match('/\?\b/', $title)) {
				$title = str_replace('?', ' ', $title);
				$title .= '?';
			} else $title = str_replace('?', ' ', $title);
			$title = str_replace('&Acirc;', '', $title);
			$title = str_replace("'", "´", $title);*/
			
			
			$output .= '<a href="'.$item['url'].'" target="_blank"> '.$title.'</a><br>'; # date("d.m.Y H:i",$item['timestamp']
		}
		$output .= '</p>';
	}
	return $output;
}

function create_html($filename, $contents)
{
	$contents = explode('<br>', $contents);
	
	$i = 0;
	$j = 0;
	$title = '';
	foreach ($contents as $line)
	{
		if (strpos($line, 'div class="age')) {
			$foo = explode('<img src="', $line);
			$title = $foo[0];
			$j = 1;
		}
		if (strpos($title, '/p>') == 1) $title = substr($title, 4);
		if (($i != 0) && ($i % 50 == 0) && (strpos($contents[($i+1)], 'div class="age') == false) && ($i < (count($contents)-5)))
		{
			$contents[$i] .= '<hr class="system-pagebreak" />'.$title.''.$contents[($i+1)];
			unset($contents[($i+1)]);
			$j = 0;
		}
		else if (($j != 0) && ($j % 5 == 0) && (strpos($contents[($i+1)], 'div class="age') == false)) $contents[$i] .= '<br>';
		$i++;
		$j++;
	}
	
	$contents = implode('<br>', $contents);
	
	file_put_contents($filename.".html", $contents);
	
}

?>
